import React, {Component} from 'react';
import {Table, Row, Col, Button, Form, Select, Input, Progress, Modal} from 'antd';
import "./index.less";
import {Link} from 'react-router-dom'
import {queryOrder, getDicByTyp, getGoodByGoodId} from "@/api/api";
import OrderForm from '@/components/OrderForm';
import ShopForm from '@/components/OrderForm/ShopForm';
const FormItem = Form.Item;
const {Option} = Select;
class orderManage extends Component {
    constructor(props) {
        super(props);
        this.updateParent = this.updateParent.bind(this);
        this.expandedRowRender= this.expandedRowRender.bind(this);
        this.state = {
            columns: [
                {
                    title: '订单编号',
                    dataIndex: 'orderId'
                },
                {
                    title: '客户名称',
                    dataIndex: 'userName'
                },
                {
                    title: '商品数量',
                    dataIndex: 'goodList',
                    render: goodList => `${goodList.length}`,
                },
                {
                    title: '订单状态',
                    dataIndex: 'statusName'
                },
                {
                    title: '下单时间',
                    dataIndex: 'createTime'
                },
                {
                    title: '操作',
                    dataIndex: 'Action',
                    width: 300,
                    align: 'center',
                    render: (text, row, index) => (
                        <Row gutter={16}>
                            <Col className="gutter-row" span={8}>
                                <Button type="primary" onClick={() => this.orderDetailsMask(row)}>详情</Button>
                            </Col>
                            <Col className="gutter-row" span={8}>
                                <Button type="primary" disabled={row.status !== '1'}>取消</Button>
                            </Col>
                            <Col className="gutter-row" span={8}>
                                <Button type="primary" disabled={row.status === '1'}>删除</Button>
                            </Col>
                        </Row>)
                }
            ],
            dataSource: [],
            pagination: {
                page: 1,
                limit: 10,
                status: '',
            },
            loading: false,
            selectedRowKeys: [],
            getStatusArr: [],
            orderVisible: false,
            shopVisible: false,
            currentRow: {},//订单详情
            shopDetailsData: {},//商品名详情
            count:0,
        };
    }
    componentDidMount() {
        this.getTable(this.state.pagination)
        this.getDicByTyp()
    }
    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }
    }
    getTable(params = {}) {
        this.setState({loading: true});
        queryOrder(params).then(res => {
            const pagination = { ...this.state.pagination };
            pagination.total = res.count;
            if (res.code == 0) {
                if(res.data=='获取失败'){
                    this.setState({
                        loading: false,
                        dataSource:[],
                        pagination,
                        count:0
                    });
                }else{
                    this.setState({
                        loading: false,
                        dataSource: res.data,
                        pagination,
                        count:res.count
                    });
                }

            }
        })
    }
    getDicByTyp() {
        let params = {
            type: 'ORDER_STATUS'
        }
        this.setState({loading: true});
        getDicByTyp(params).then(res => {
            if (res.code == 0) {
                this.setState({
                    getStatusArr: res.data,
                    loading: false
                })
            }
        })
    }
    expandedRowRender(record) {
        for (let i = 0; i < record.goodList.length; i++) {
            let item = record.goodList[i]
            item["key"] = i
        }
        const columns = [
            {title: '商品名称', dataIndex: 'goodName', key: 'goodName'},
            {title: '商品类型（一级）', dataIndex: 'oneTypeName', key: 'oneTypeName'},
            {title: '商品类型（二级级）', dataIndex: 'twoTypeName', key: 'twoTypeName'},
            {title: '商品状态', dataIndex: 'statusName', key: 'statusName'},
            {
                title: '商品进度',
                key: 'goodProcess',
                width: '200px',
                render: (text, row, index) => (
                    <Progress percent={Number(row.goodProcess)} status="active"/>
                ),
            },
            {
                title: '操作',
                dataIndex: 'operation',
                key: 'operation',
                width: '230px',
                render: (text, row) => (
                    <Row gutter={16}>
                        <Col className="gutter-row" span={8}>
                            <Button type="primary">详情</Button>
                        </Col>
                        <Col className="gutter-row" span={8}>
                            <Button type="primary" disabled={row.status !== '3' } >
                                <Link to= {{ pathname : '/resultView' , query : { id :`${row.id}` }}}>查看</Link>
                            </Button>
                        </Col>
                    </Row>),
            },
        ];

        return <Table columns={columns} dataSource={record.goodList} rowKey={record => record.id} pagination={false}/>;
    }
    handleOk = (val) => {
        if (val == 'shopVisible') {
            this.setState({shopVisible: false});
        } else {
            this.setState({orderVisible: false});
        }
    };
    handleCancel(val) {
        if (val == 'shopVisible') {
            this.setState({shopVisible: false});
        } else {
            this.setState({orderVisible: false});
        }
    };
    orderDetailsMask = (record) => {
        this.setState({currentRow: record, orderVisible: true});
    }
    updateParent(val, id) {
        getGoodByGoodId({goodId: id}).then(res => {
            if (res.code == 0) {
                this.setState({
                    shopDetailsData: res.data,
                    shopVisible: val
                })
            }
        })
    }
    handleSearch = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            let params = {
                status: values.status || '',
                limit: 10,
                page: 1,
            }
            if(values.orderId!=undefined){
                params.orderId=values.orderId
            }
            if (values) {
                this.getTable(params)
            }
        });
    };
    handleReset = () => {
        this.props.form.resetFields();
        this.getTable(this.state.pagination)
    };
    // 切换分页
    handleTableChange = page => {
        console.log(this.state.pagination)
        const pager = { ...this.state.pagination };
        pager.page = page;
        delete pager.total;
        this.getTable(pager);
    };
    onShowSizeChange(pageSize,current){

    }
    render() {
        const {getFieldDecorator} = this.props.form;
        const getStatusOption = this.state.getStatusArr.map((item, index) => <Option value={item.codeKey} key={item.id}>{item.codeValue}</Option>)

            const totals=this.state.count
        const paginationProps = {
            onChange: page => this.handleTableChange(page),
            onShowSizeChange: (current, pageSize) => this.onShowSizeChange(current, pageSize), //  pageSize 变化的回调
            ...this.state.pagination,
            showSizeChanger: true,
            showTotal: () => `共${totals}条`,
        };

        return (
            <div className="site-card-wrapper ">
                <div className="shadow-radius">
                    <Form className="search-form" style={{paddingBottom: 0}}>
                        <Row gutter={24}>
                            <Col span={5}>
                                <FormItem label="订单号">
                                    {getFieldDecorator('orderId')(
                                        <Input placeholder="请输入订单号"/>
                                    )}

                                </FormItem>
                            </Col>
                            <Col span={5}>
                                <FormItem label="订单状态">
                                    {getFieldDecorator('status')(
                                        <Select placeholder="请选择">
                                            {getStatusOption}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={2} style={{marginRight: '10px', display: 'flex'}} className="serarch-btns">
                                <FormItem>
                                    <Button icon="search" type="primary" htmlType="submit" className={'btn'}
                                            onClick={this.handleSearch}>
                                        查询
                                    </Button>
                                </FormItem>
                                <FormItem>
                                    <Button className={'btn'}  onClick={this.handleReset}>
                                        重置
                                    </Button>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                    <Table bordered columns={this.state.columns} dataSource={this.state.dataSource}
                           expandedRowRender={this.expandedRowRender} rowKey={record => record.id}
                           loading={this.state.loading}  pagination={paginationProps}/>
                </div>
                <Modal title="订单详情" width={'800px'} visible={this.state.orderVisible}
                       onOk={() => this.handleOk(this.state.orderVisible)}
                       onCancel={() => this.handleCancel('orderVisible')} footer={null}>
                    <OrderForm data={this.state.currentRow} orderVisible={this.state.orderVisible}
                               shopVisible={this.state.shopVisible} updateParent={this.updateParent}/>
                </Modal>
                <Modal title="商品详情" width={'800px'} visible={this.state.shopVisible}
                       onOk={() => this.handleOk(this.state.shopVisible)}
                       onCancel={() => this.handleCancel('shopVisible')} footer={null}>
                    <ShopForm data={this.state.shopDetailsData} orderVisible={this.state.shopVisible}
                              updateParent={this.updateParent}/>
                </Modal>
            </div>
        );
    }
}

export default Form.create()(orderManage);
